package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package com.qf.utils
 * @description: ${TODO}
 * @date 2022/6/22 10:19
 * 数据源工具类
 */
public class DataSourceUtils {
    //创建数据源对象
    private static DruidDataSource dataSource;
    //ThreadLocal 线程本地变量
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    //静态代码块
    static {
        Properties properties=new Properties();
        InputStream is=DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
            is.close();
            //初始化
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池失败");
        }
    }

    public static DataSource getDataSource(){
        return  dataSource;
    }

    public static Connection getConnection(){
        Connection conn = threadLocal.get();
        if(conn==null){
            try {
                conn=getDataSource().getConnection();
                //绑定到threadLocal
                threadLocal.set(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }
    public static void closeAll(ResultSet rs, Statement stat,Connection conn){
        try {
            if (rs != null) {
                rs.close();
            }
            if (stat != null) {
                stat.close();
            }
            if (conn != null) {
                if(conn.getAutoCommit()) {
                    conn.close();
                    //解除绑定
                    threadLocal.remove();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //四个与事务有关的方法
    public static void begin() throws SQLException{
        Connection conn = getConnection();
        if(conn!=null){
            conn.setAutoCommit(false);
        }
    }
    public static void commit() throws SQLException{
        Connection conn = getConnection();
        if(conn!=null){
            conn.commit();
        }
    }

    public static void rollback() throws SQLException{
        Connection conn = getConnection();
        if(conn!=null){
            conn.rollback();
        }
    }

    public static void close() throws SQLException{
        Connection conn = getConnection();
        if(conn!=null){
            conn.close();
            //解除绑定
            threadLocal.remove();
        }
    }

}
